package com.iot08.admin.service;

import com.iot08.common.entity.app.DeviceNotification;
import com.iot08.common.entity.app.OpenidConfig;
import com.iot08.common.service.base.BaseService;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2020/12/31 14:53
 */
@Service
public class OpenidConfigService extends BaseService<OpenidConfig> {

    @Resource
    private DeviceNotificationService deviceNotificationService;

    /**
     * @param notifyId
     * @param uuids
     * @time: 2020/12/31 15:38
     * @author: Rock
     * @version 1.0
     */
    public void checkUpdateShowMsgIdList(String notifyId, Set<String> uuids) {
        Date now = new Date();
        for (String id : uuids) {
            OpenidConfig uc = this.findById(id);
            if (uc == null) {
                continue;
            }
            if (uc.getShowMsgIdList() == null) {
                uc.setShowMsgIdList(new ArrayList<>());
            }
            if (uc.getShowMsgIdList().size() > 0) {
                Iterator<String> it = uc.getShowMsgIdList().iterator();
                while (it.hasNext()) {
                    DeviceNotification dn = deviceNotificationService.findById(new ObjectId(it.next()));
                    if (dn == null || dn.getExpiryAt() == null || now.after(dn.getExpiryAt())) {
                        it.remove();
                    }
                }
            }
            uc.getShowMsgIdList().add(notifyId);
            Update update = new Update();
            update.set("showMsgIdList", uc.getShowMsgIdList());
            this.updateById(id, update);
        }
    }

}
